"""
用户模型
"""
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey
from src.database import db
from datetime import datetime

class User(db.Model):
    """用户模型"""
    __tablename__ = 'users'
    
    id = Column(Integer, primary_key=True)
    username = Column(String(80), unique=True, nullable=False, index=True)
    email = Column(String(120), unique=True, nullable=True, index=True)
    password_hash = Column(String(255), nullable=False)
    student_id = Column(String(50), unique=True, nullable=True, index=True)  # 学号
    role = Column(String(20), default='student', nullable=False)  # student, teacher, admin
    is_active = Column(Boolean, default=True)
    last_login = Column(DateTime, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'student_id': self.student_id,
            'role': self.role,
            'is_active': self.is_active,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'last_login': self.last_login.isoformat() if self.last_login else None
        }
    
    def __repr__(self):
        return f'<User {self.username}>'

class UserRole(db.Model):
    """用户角色关联表"""
    __tablename__ = 'user_roles'
    
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    role = Column(String(20), nullable=False)  # student, teacher, admin, super_admin
    created_at = Column(DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f'<UserRole user_id={self.user_id} role={self.role}>'

class Permission(db.Model):
    """权限模型"""
    __tablename__ = 'permissions'
    
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)  # 权限名称
    resource = Column(String(50), nullable=False)  # 资源名称
    action = Column(String(50), nullable=False)  # 操作名称
    description = Column(String(255), nullable=True)
    
    def __repr__(self):
        return f'<Permission {self.name}>'

class RolePermission(db.Model):
    """角色权限关联表"""
    __tablename__ = 'role_permissions'
    
    id = Column(Integer, primary_key=True)
    role = Column(String(20), nullable=False)  # 角色名称
    permission_id = Column(Integer, ForeignKey('permissions.id'), nullable=False)
    
    def __repr__(self):
        return f'<RolePermission role={self.role} permission_id={self.permission_id}>'

